package com.ruoyi.common.hanlder;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.FillFieldEnum;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.Objects;

/**
 * @author dongjunliang
 * @version 1.0.0
 * @ClassName MbatisCustomMetaObjectHandle.java
 * @Description TODO
 * @createTime 2024年12月23日 13:03:00
 */
@Component
@Slf4j
public class MybatisCustomMetaObjectHandle implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        boolean hasCreateTime = metaObject.hasSetter(FillFieldEnum.CREATETIME.getValue());
        boolean hasUpdateTime = metaObject.hasSetter(FillFieldEnum.UPDATETIME.getValue());

        if (hasCreateTime) {
            strictInsertFill(metaObject, FillFieldEnum.CREATETIME.getValue(), Date.class, DateUtils.getNowDate() );
        }
        if (hasUpdateTime) {
            strictInsertFill(metaObject, FillFieldEnum.UPDATETIME.getValue(),  Date.class, DateUtils.getNowDate());
        }
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if(Objects.nonNull(loginUser)){
                strictInsertFill(metaObject,FillFieldEnum.CREATEBY.getValue(),String.class,loginUser.getUsername());
            }
        }catch (Exception e){
            log.warn("插入对象数据时，当前登录用户异常:{}",e.getMessage());
            strictInsertFill(metaObject,FillFieldEnum.CREATEBY.getValue(),String.class,"system");
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        boolean hasUpdateTime = metaObject.hasSetter(FillFieldEnum.UPDATETIME.getValue());
        if (hasUpdateTime) {
            strictUpdateFill(metaObject, FillFieldEnum.UPDATETIME.getValue(), Date.class, DateUtils.getNowDate());
        }

        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (Objects.nonNull(loginUser)) {
                strictUpdateFill(metaObject, FillFieldEnum.UPDATEBY.getValue(), String.class, loginUser.getUsername());
            }
        } catch (Exception e) {
            log.warn("更新对象数据时，当前登录用户异常:{}", e.getMessage());
            strictUpdateFill(metaObject, FillFieldEnum.UPDATEBY.getValue(), String.class, "system");
        }
    }
}
